#include "stdafx.h"
#include "RenderTarget.h"

namespace Reign
{namespace Video
{namespace D3D10
{
	#pragma region Constructors
	RenderTarget::RenderTarget(DisposableI^ parent, string^ fileName)
	: Texture2D(parent, fileName)
	{}

	RenderTarget::RenderTarget(DisposableI^ parent, string^ fileName, int width, int height, MultiSampleTypes multiSampleType, SurfaceFormats surfaceFormat, RenderTargetUsage renderTargetUsage)
	: Texture2D(parent, fileName, width, height, false, multiSampleType, surfaceFormat, renderTargetUsage)
	{}

	RenderTarget::RenderTarget(DisposableI^ parent, int width, int height, MultiSampleTypes multiSampleType, SurfaceFormats surfaceFormat, RenderTargetUsage renderTargetUsage)
	: Texture2D(parent, width, height, false, multiSampleType, surfaceFormat, renderTargetUsage, BufferUsages::Default)
	{}

	void RenderTarget::init(DisposableI^ parent, string^ fileName, int width, int height, bool generateMipmaps, MultiSampleTypes multiSampleType, SurfaceFormats surfaceFormat, RenderTargetUsage renderTargetUsage, BufferUsages usage, bool isRenderTarget)
	{
		null();
		Texture2D::init(parent, fileName, width, height, false, multiSampleType, surfaceFormat, renderTargetUsage, usage, true);

		try
		{
			DXGI_FORMAT surfaceFormatD3D = Video::surfaceFormat(surfaceFormat);

			D3D10_RENDER_TARGET_VIEW_DESC desc;
			ZeroMemory(&desc, sizeof(D3D10_RENDER_TARGET_VIEW_DESC));
			desc.Format = surfaceFormatD3D;
			desc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D;
			desc.Texture2D.MipSlice = 0;
			ID3D10RenderTargetView* renderTargetTEMP = 0;
			if (FAILED(video->Device->CreateRenderTargetView(texture, &desc, &renderTargetTEMP)))
			{
				Debug::ThrowError(L"RenderTarget", L"Failed to create RenderTargetView");
			}
			renderTarget = renderTargetTEMP;
		}
		catch (Exception^ ex)
		{
			delete this;
			throw ex;
		}
	}

	RenderTarget::~RenderTarget()
	{
		disposeChilderen();
		if (renderTarget) renderTarget->Release();
		null();
	}

	void RenderTarget::null()
	{
		renderTarget = 0;
	}
	#pragma endregion

	#pragma region Methods
	void RenderTarget::Enable()
	{
		video->removeActiveResource(ShaderResource);
		ID3D10RenderTargetView* renderTargetTEMP = renderTarget;
		video->Device->OMSetRenderTargets(1, &renderTargetTEMP, 0);
		video->currentRenderTarget = renderTarget;
		video->currentDepthStencil = 0;
	}

	void RenderTarget::Enable(DepthStencilI^ depthStencil)
	{
		video->removeActiveResource(ShaderResource);
		ID3D10RenderTargetView* renderTargetTEMP = renderTarget;
		video->currentRenderTarget = renderTarget;
		
		if (depthStencil != nullptr)
		{
			ID3D10DepthStencilView* surface = ((DepthStencil^)depthStencil)->Surface;
			video->currentDepthStencil = surface;
			video->Device->OMSetRenderTargets(1, &renderTargetTEMP, surface);
		}
		else
		{
			video->Device->OMSetRenderTargets(1, &renderTargetTEMP, 0);
		}
	}
	#pragma endregion
}
}
}